package deanandjames.image;

import java.awt.*;
import java.awt.image.BufferedImage;

public class Ribbon {
	private final BufferedImage image;
	private boolean isMovingLeft;
	private boolean isMovingRight;
	private final int moveSize;
	private final int panelHeight;
	private final int panelWidth;
	private final int width;
	private int xImageHead;

	public Ribbon(int panelWidth, int panelHeight, BufferedImage image, int moveSize) {
		this.panelWidth = panelWidth;
		this.panelHeight = panelHeight;
		this.image = image;
		width = image.getWidth();
		if (width < panelWidth) {
			System.out.println("Ribbon width < panel width");
		}
		this.moveSize = moveSize;
		isMovingRight = false;
		isMovingLeft = false;
		xImageHead = 0;
	}

	public void display(Graphics g) {
		if (xImageHead == 0) {
			draw(g, image, 0, panelWidth, 0, panelWidth);
		} else if (xImageHead > 0 && xImageHead < panelWidth) {
			draw(g, image, 0, xImageHead, width - xImageHead, width);
			draw(g, image, xImageHead, panelWidth, 0, panelWidth - xImageHead);
		} else if (xImageHead >= panelWidth) {
			draw(g, image, 0, panelWidth, width - xImageHead, width - xImageHead + panelWidth);
		} else if (xImageHead < 0 && xImageHead >= panelWidth - width) {
			draw(g, image, 0, panelWidth, -xImageHead, panelWidth - xImageHead);
		} else if (xImageHead < panelWidth - width) {
			draw(g, image, 0, width + xImageHead, -xImageHead, width);
			draw(g, image, width + xImageHead, panelWidth, 0, panelWidth - width - xImageHead);
		}
	}

	public void moveLeft() {
		isMovingRight = false;
		isMovingLeft = true;
	}

	public void moveRight() {
		isMovingRight = true;
		isMovingLeft = false;
	}

	public void stayStill() {
		isMovingRight = false;
		isMovingLeft = false;
	}

	public void update() {
		if (isMovingRight) {
			xImageHead = (xImageHead + moveSize) % width;
		} else if (isMovingLeft) {
			xImageHead = (xImageHead - moveSize) % width;
		}
	}

	private void draw(Graphics g, BufferedImage image, int scrX1, int scrX2, int imX1, int imX2) {
		g.drawImage(image, scrX1, 0, scrX2, panelHeight, imX1, 0, imX2, panelHeight, null);
	}
}